import store from '@/store'

import axios from 'axios'
import router from '@/router'
import { Message } from 'element-ui'
import { getTimeStamp } from '@/utils/auth'
const timeOut = 3600
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000
}) // 创建实例
service.interceptors.request.use(config => {
  //在这个位置需要统一注入token
  if (store.getters.token) {
    if (IsCheckTimeOut()) {
      store.dispatch('user/logout')
      router.push('/login')
      return Promise.reject(new Error('token超时了'))
    }
    config.headers['Authorization'] = `Bearer ${store.getters.token}`
  }
  return config
}, error => {
  return Promise.reject(error)
}) // 请求拦截器
service.interceptors.response.use(response => {
  //axios默认加了一层data
  const { success, message, data } = response.data
  if (success) {
    return data
  } else {
    Message.error(message)  //提示错误消息
    return Promise.reject(new Error(message))
  }
}, error => {

  if (error.response && error.response.data && error.response.data.code === 10002) {
    store.dispatch('user/logout')
    router.push('/login')

  } else {
    Message.error(error.message) //提示错误信息
  }
  return Promise.reject(error)

}) // 响应拦截器

//超时
function IsCheckTimeOut () {
  var currentTime = Date.now() //当前时间戳
  var timeStamp = getTimeStamp()//缓存时间戳
  return (currentTime - timeStamp) / 1000 > timeOut
}
export default service
